<template>
  <div>
    <div class="container-xl height">
      <div class="row">
        <h2 class="col">{{ data.name }}</h2>
        <div class="col text-right">
          <span class="t-info">
            <span>成员</span>
            &nbsp;
            <span>
              {{
                teamusers.filter((e) => e.jurisdiction === "0").length + 1
              }}
            </span>
            &nbsp; &nbsp;
            <span>创建时间</span>
            &nbsp;
            <span>{{ toLocaleDateString(data.createdAt) }}</span>
            &nbsp;
            <span>{{ data.description }}</span>
          </span>
        </div>
      </div>
    </div>
    <div class="container-xl ">
      <el-button-group class="row my-home-div my-home-divbuttom" :style="{ display: 'flex' }">
        <router-link v-slot="{ navigate, isActive }" custom :to="{
          name: '团队动态',
          params: { ID }
        }">
          <el-button class="col" :type="isActive ? 'primary' : 'default'" @click="navigate" name="团队动态">
            &nbsp;&nbsp;首页&nbsp;&nbsp; </el-button>
        </router-link>
        <router-link v-slot="{ navigate, isActive }" custom :to="{
          name: '团队题单',
          params: { ID }
        }">
          <el-button class="col" :type="isActive ? 'primary' : 'default'" @click="navigate" name="团队题单">&nbsp;&nbsp; 题单
            &nbsp;&nbsp;
          </el-button>
        </router-link>
        <router-link v-slot="{ navigate, isActive }" custom :to="{
          name: '团队题目',
          params: { ID }
        }">
          <el-button class="col" :type="isActive ? 'primary' : 'default'" @click="navigate" name="团队题目">&nbsp;&nbsp; 题目
            &nbsp;&nbsp;
          </el-button>
        </router-link>
        <router-link v-slot="{ navigate, isActive }" custom :to="{
          name: '团队工作',
          params: { ID }
        }">
          <el-button class="col" :type="isActive ? 'primary' : 'default'" v-if="Team.grade" @click="navigate"
            name="团队工作">&nbsp;&nbsp; 任务
            &nbsp;&nbsp;
          </el-button>
        </router-link>
        <router-link v-slot="{ navigate, isActive }" custom :to="{
          name: '团队通知',
          params: { ID }
        }">
          <el-button class="col" :type="isActive ? 'primary' : 'default'" @click="navigate" name="团队通知">&nbsp;&nbsp; 通知
            &nbsp;&nbsp;
          </el-button>
        </router-link>
        <router-link v-slot="{ navigate, isActive }" custom :to="{
          name: '团队组员',
          params: { ID }
        }">
          <el-button class="col" :type="isActive ? 'primary' : 'default'" @click="navigate" name="团队组员">&nbsp;&nbsp; 组员
            &nbsp;&nbsp;
          </el-button>
        </router-link>
        <router-link v-slot="{ navigate, isActive }" custom :to="{
          name: '团队数据',
          params: { ID }
        }">
          <el-button class="col" :type="isActive ? 'primary' : 'default'" @click="navigate" name="团队数据">&nbsp;&nbsp; 数据
            &nbsp;&nbsp;
          </el-button>
        </router-link>
        <router-link v-slot="{ navigate, isActive }" custom :to="{
          name: '团队比赛',
          params: { ID }
        }">
          <el-button class="col" :type="isActive ? 'primary' : 'default'" @click="navigate" name="团队比赛">&nbsp;&nbsp; 比赛
            &nbsp;&nbsp;
          </el-button>
        </router-link>
        <router-link v-slot="{ navigate, isActive }" v-if="!data.isadmin" custom :to="{
          name: '团队文件',
          params: { ID }
        }">
          <el-button class="col" :type="isActive ? 'primary' : 'default'" @click="navigate" name="团队文件">
            &nbsp;&nbsp; 资料
            &nbsp;&nbsp;</el-button>
        </router-link>
        <router-link v-slot="{ navigate, isActive }" custom :to="{
          name: '团队设置',
          params: { ID }
        }">
          <el-button class="col" :type="isActive ? 'primary' : 'default'" v-if="isAdmin" @click="navigate" name="团队设置">
            &nbsp;&nbsp; 设置
            &nbsp;&nbsp;</el-button>
        </router-link>
      </el-button-group>
    </div>
    <router-view v-if="show" v-bind="{
      data,
      changeteam,
      isAdmin,
      teamusers,
      user,
      isinteam,
      task,
      getUsers,
      gettask,
      badge,
      flow,
      setflow
    }"></router-view>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from "element-plus";
import {
  computed,
  onMounted,
  reactive,
  ref,
  toRefs,
  watch,
} from "vue";
import {
  onBeforeRouteUpdate,
  useRouter
} from "vue-router";
import { useStore } from "vuex";
import { Team } from "../../../admin/views/data";
import {
  asyncgetteam,
  asyncgetteamflow,
  asyncselectteamselectuser,
  asyncteamchangeteam,
  asyncteamselecttask,
} from "../../../api/index";
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { toLocaleDateString } from "../../../util/time";
const p = defineProps<{ ID?: number }>()
const { ID } = toRefs(p);
const router = useRouter();
const data = reactive(Object.assign({}, Team));
const show = ref(false)

const store = useStore(Storekey);
const user = computed<Studycodemodel.Iuser>(() => {
  return store.getters.getuser;
});

const task = reactive<{ count: number; rows: Studycodemodel.Iteamtask[] }>({
  count: 0,
  rows: [],
});

const isinteam = computed(() => {
  if (!user.value) return false;
  if (data?.userid === user.value.ID) return true;
  if (
    user.value.ID &&
    data?.teamuser?.map((v) => v.userid).includes(user.value.ID)
  )
    return true;
  return false;
});


const teamusers = ref<Studycodemodel.Iteamuser[]>([]);

watch(
  () => p.ID,
  () => {

    start().then(() => {
      getUsers();
      gettask();
    });
  }
);

const flow = ref<Studycodemodel.Iteamflow>()

async function setflow() {
  try {
    flow.value = await asyncgetteamflow({ teamid: ID?.value })

  } catch (e) {
    flow.value = undefined
    console.log(e)
  }
}

async function start() {
  if (typeof ID?.value === "number") {
    const d = await asyncgetteam({ ID: ID.value });
    Object.assign(data, d);
  } else {
    // ElMessage.error("没有查询到");
  }
  setflow()
}

const badge = reactive({ sett: false, });

async function getUsers() {
  if (typeof ID?.value === "number") {
    try {
      teamusers.value = await asyncselectteamselectuser({
        teamid: ID.value,
      });
    } catch (e) {
      teamusers.value = []
    }
    // 团队创建者或者销售助教
    const userid = data.userid === user.value?.ID || user.value?.remarks === '销售助教'
    if (userid) {
      badge.sett = true;
      return
    }
    const f = teamusers.value.find(e => e.userid === user.value?.ID)
    if (f) {
      const m = Number(f.jurisdiction) > 1
      if (m) {
        badge.sett = true;
      }
    } else {
      badge.sett = false;
      if (!store.state.science) {
        ElMessage.error('没有权限')
        router.push('/')
      }
    }

  }
}

onBeforeRouteUpdate((to, from, next) => {
  if (to.name === "团队设置") {
    if (isAdmin.value === 1) {
      next();
    } else {
      ElMessage.error("只有管理员可以进行设置");
    }
  } else {
    next();
  }
});

async function gettask(_offset?: number) {
  if (typeof ID?.value === "number") {
    const data = await asyncteamselecttask({
      teamid: ID.value,
      _offset,
      _limit: 10,
    });
    Object.assign(task, data);
  }
}

onMounted(() => {
  data.ID = undefined

  start().then(async () => {
    await getUsers();
    await gettask();
    show.value = true
  });
});

watch(
  () => user,
  () => {
    start();
  }
);

const isAdmin = computed(() => {
  if (!user.value) return 0;
  if (data?.userid === user.value.ID) return 1;
  const a = data?.teamuser?.find((v) => v.userid === user.value.ID);
  if (a) {
    return a.isAdmin;
  }
  if (user.value.remarks === "销售助教") return 1;
  return 0;
});

async function changeteam(body: Studycodemodel.Iteam) {
  if (isAdmin.value === 1 && data?.ID) {
    Object.assign(body, { teamid: data.ID });
    await asyncteamchangeteam(body);

    await start();
  } else {
    ElMessage.error("你不是管理员无法更改");
  }
}
</script>

<style scoped>
.height {
  padding-top: 32px;
  padding-bottom: 24px;
}

.height h2 {
  font-weight: 700;
  font-size: 24px;
}

.t-info {
  font-size: 12px;
}

.my-home-div {
  border: 1px solid rgba(117, 117, 117, 0.4);
  box-shadow: 0px 0.3px 0.9px rgba(0, 0, 0, 0.1), 0px 1.6px 3.6px rgba(0, 0, 0, 0.13);
  border-radius: 4px;
  overflow-x: hidden;
  background-color: #fff;
  margin-bottom: 24px;
}

.my-home-div-line {
  background: linear-gradient(180deg, rgba(255, 255, 255, 0) 97.4%, rgba(0, 0, 0, 0.6) 100%, rgba(0, 0, 0, 0.2) 100%, rgba(0, 0, 0, 0.6) 100%);
  height: 48px;
  line-height: 47px;
  font-size: 16px;
  padding-left: 14px;
  padding-right: 14px;
  font-weight: 700;
}

.my-home-divbuttom button {
  border-top-width: 0;
  border-bottom-width: 0;
}

.my-home-divbuttom button:last-child {
  border-right-width: 0;
}

.my-home-divbuttom button:first-child {
  border-left-width: 0;
}

.el-button-group .el-button {
  --el-button-border-color: rgba(117, 117, 117, 0.4);
  --el-button-hover-border-color: rgba(117, 117, 117, 0.4);
}
</style>
